/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RemoteObjectListerUI.java
 *
 * Created on Mar 17, 2011, 8:29:49 PM
 */
package fss.client;

import fss.remote.RemoteService;
import fss.remote.ServiceRegistry;
import fss.util.rmi.RmiId;
import fss.util.rmi.RmiUtils;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JTextArea;

/**
 *
 * @author hieu
 */
public class RemoteObjectListerUI extends javax.swing.JFrame
{

  /** Creates new form RemoteObjectListerUI */
  public RemoteObjectListerUI()
  {
    initComponents();
    setupUI();
    setUpModel();
    setUpListener();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    hostLabel = new javax.swing.JLabel();
    hostTextField = new javax.swing.JTextField();
    portLabel = new javax.swing.JLabel();
    portTextField = new javax.swing.JTextField();
    applyButton = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    listOutput = new javax.swing.JList();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Remote Objects Lister");

    hostLabel.setText("Host:");

    portLabel.setText("Port:");

    applyButton.setText("Show All Remote Objects");
    applyButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        applyButtonActionPerformed(evt);
      }
    });

    listOutput.setToolTipText("Click on the Remote Object for its details");
    jScrollPane1.setViewportView(listOutput);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
          .addComponent(applyButton, javax.swing.GroupLayout.Alignment.CENTER)
          .addGroup(javax.swing.GroupLayout.Alignment.CENTER, layout.createSequentialGroup()
            .addComponent(hostLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(hostTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(portLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addGap(29, 29, 29))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(hostLabel)
          .addComponent(hostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(portLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(applyButton)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void applyButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_applyButtonActionPerformed
  {//GEN-HEADEREND:event_applyButtonActionPerformed
    if (!hostTextField.getText().isEmpty()
            && !portTextField.getText().isEmpty())
    {
      boolean tPortValid = false;
      int tPortNum = 0;
      try
      {
        tPortNum = Integer.parseInt(portTextField.getText());
        tPortValid = true;
      }
      catch (Exception aEx)
      {
        System.out.println("Port numer needs to be numeric");
      }

      if (tPortValid)
      {
        try
        {
          HashMap<String, String> tRemoteObjects =
                RmiUtils.listRmiRegistryRemoteObjects(hostTextField.getText(),
                tPortNum);
          for (String tName : tRemoteObjects.keySet())
          {
            RemoteObjectListItem tItem = new RemoteObjectListItem(
              hostTextField.getText(),
              tName,
              tRemoteObjects.get(tName),
              tPortNum);
            listModel.addElement(tItem);
          }
        }
        catch (Exception aEx)
        {
          System.out.println ("Cannot retrieve remote object list.");
          aEx.printStackTrace();
        }
      }
    }
  }//GEN-LAST:event_applyButtonActionPerformed

  /**
   * Set up the model
   */
  private void setUpModel()
  {
    listModel = new DefaultListModel();
    listOutput.setModel(listModel);
  }
  
  private void setUpListener()
  {
    listOutput.addMouseListener(new MouseListener() {

      @Override
      public void mouseClicked(MouseEvent e)
      {
        int tIndex = listOutput.locationToIndex(e.getPoint());
        RemoteObjectListItem tItem =
          (RemoteObjectListItem) listModel.getElementAt(tIndex);
        RmiId tId = new RmiId(tItem.getHost(),
                                              tItem.getName(),
                                              tItem.getPort());
        if (tItem.getClassName().equals("fss.remote.RemoteService"))
        {
          RemoteService tRemote = (RemoteService) RmiUtils.getRemoteObject(tId);
        }
        else if (tItem.getClassName().equals("fss.remote.ServiceRegistry"))
        {
          ServiceRegistry tRemote = (ServiceRegistry) RmiUtils.getRemoteObject(tId);
        }

        try
        {
          StringBuilder tOutput = new StringBuilder();
          tOutput.append("Class name: ").append(tItem.getClassName()).append(" has following methods:\n");
          Class tClass = Class.forName(tItem.getClassName());
          for (Method tMethod : tClass.getMethods())
          {
            tOutput.append(" => ").append(tMethod.getName()).append("\n");
          }
          textArea.setText(tOutput.toString());
          popupPanel.setVisible(true);
          

        } catch (Exception aEx)
        {
          System.out.println ("Unable to load the Remote Object class");
        }
      }

      @Override
      public void mousePressed(MouseEvent e)
      {
        //Do nothing
      }

      @Override
      public void mouseReleased(MouseEvent e)
      {
        //Do nothing
      }

      @Override
      public void mouseEntered(MouseEvent e)
      {
        //Do nothing
      }

      @Override
      public void mouseExited(MouseEvent e)
      {
        //Do nothing
      }
    });
  }

  private void setupUI()
  {
    popupPanel = new JFrame("Remote Object Details");
    textArea = new JTextArea();
    popupPanel.setVisible(false);
    textArea.setEditable(false);
    textArea.setCursor(null);
    textArea.setOpaque(false);
    textArea.setFocusable(false);
    popupPanel.setSize(400, 400);
    textArea.setBounds(0, 0, 400, 400);
    popupPanel.add(textArea);
  }
  /**
   * @param aArgs the command line arguments
   */
  public static void main(String aArgs[])
  {
    java.awt.EventQueue.invokeLater(new Runnable()
    {

      @Override
      public void run()
      {
        new RemoteObjectListerUI().setVisible(true);
      }
    });
  }

  // Other variables
  private DefaultListModel listModel;
  private JFrame popupPanel;
  private JTextArea textArea;
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton applyButton;
  private javax.swing.JLabel hostLabel;
  private javax.swing.JTextField hostTextField;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JList listOutput;
  private javax.swing.JLabel portLabel;
  private javax.swing.JTextField portTextField;
  // End of variables declaration//GEN-END:variables

}
